package com.techsoul.module.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.constant.ApiConstants;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.security.pojo.LoginUser;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.system.mapper.GeneralSeqMapper;
import com.techsoul.module.system.pojo.entity.GeneralSeq;
import com.techsoul.module.system.pojo.param.GeneralSeqSaveParam;
import com.techsoul.module.system.pojo.param.GeneralSeqSearchParam;
import com.techsoul.module.system.pojo.vo.GeneralSeqVo;
import com.techsoul.module.system.service.IGeneralSeqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 通用序列号 Service实现
 * 
 * @author liuen
 * @date 2020-12-29
 */
@Service
@Transactional(readOnly = true)
public class GeneralSeqServiceImpl implements IGeneralSeqService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private GeneralSeqMapper mapper;

    @Autowired
    private TokenService tokenService;

    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(GeneralSeqSaveParam params) {
       // LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        GeneralSeq entity = new GeneralSeq();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "")
                .preInsert(ApiConstants.DEFAULT_USER_ID );
        this.mapper.insert(entity);
        return entity.getId();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(GeneralSeqSaveParam params) {
        GeneralSeq entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
       // LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(ApiConstants.DEFAULT_USER_ID);
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 生成序列表
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String generateSeq(GeneralSeqSaveParam params) {
        if (StringUtils.isNotBlank(params.getBizCode())) {
            if (StringUtils.isNotBlank(params.getPrefixNo())) {
                return this.generateSeq(params.getBizCode(), params.getPrefixNo());
            }
            return this.generateSeq(params.getBizCode());
        }
        return null;
    }

    /**
     * 生成序列表
     * @param bizCode 业务编码，如：业务表名称
     * @return
     */
    @Override
    public String generateSeq(String bizCode) {
        return this.generateSeq(bizCode, null);
    }

    /**
     * 生成序列表
     * @param bizCode 业务编码，如：业务表名称
     * @param prefixNo 前缀，如：日期
     * @return
     */
    @Override
    public String generateSeq(String bizCode, String prefixNo) {
        // 设置前缀
        if (StringUtils.isBlank(prefixNo)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
            prefixNo = sdf.format(new Date());
        }
        // 根据bizCode和prefixNo，查询编号生成信息
        GeneralSeqSearchParam generalSeqSearchParam = new GeneralSeqSearchParam();
        generalSeqSearchParam.setBizCode(bizCode)
                .setPrefixNo(prefixNo);
        List<GeneralSeqVo> allGeneralSeqTabVoList = this.findAll(generalSeqSearchParam);
        // 设置编号
        BigDecimal serialNo = new BigDecimal(1);
        GeneralSeqSaveParam generalSeqSaveParam = new GeneralSeqSaveParam();
        if (ListUtils.isNotEmpty(allGeneralSeqTabVoList)) {
            // 更新编号生成信息
            GeneralSeqVo generalSeqVo = allGeneralSeqTabVoList.get(0);
            BeanUtils.copyProperties(generalSeqVo, generalSeqSaveParam);
            serialNo = generalSeqVo.getSerialNo().add(BigDecimal.valueOf(1));
            generalSeqVo.setSerialNo(serialNo);
            generalSeqSaveParam.setSerialNo(serialNo);
            this.update(generalSeqSaveParam);
        } else {
            // 新增编号生成信息
            generalSeqSaveParam.setBizCode(bizCode)
                    .setPrefixNo(prefixNo)
                    .setSerialNo(serialNo);
            this.insert(generalSeqSaveParam);
        }
        // 格式化序列号
        DecimalFormat df = new DecimalFormat("000000");
        return prefixNo + df.format(serialNo);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public GeneralSeqVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<GeneralSeqVo> findAll(GeneralSeqSearchParam params) {
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<GeneralSeqVo> findAll(GeneralSeqSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }

}
